/*
 * @Date: 2022-11-20 18:44:03
 * @Autor: lx
 * @LastEditors: lipengxi 2899952565@qq.com
 * @LastEditTime: 2022-12-04 22:33:15
 * @FilePath: /lg-study/Part3_Vue/vue-router/src/lxrouter/index.js
 */
let _Vue = null
export default class LxRouter {
    constructor(options) {
        this.mode = options.mode || "hash";
        this.routeMap = {};
        this.options = options
        this.data = _Vue.observable({
            current: "/"
        })
    }

    /**
     * @description: 路由$router挂载vue原型后的初始化
     * @return {*}
     * @author: lx
     */
    init() {
        this.createRouterMap();
        this.initComponents()
        this.initEvent()
    }

    /**
     * @description: Vue.use()执行的方法
     * @param {*} Vue
     * @return {*}
     * @author: lx
     */
    static install(Vue) {
        // 1.判断插件是否已经安装
        if (LxRouter.install.stalled) {
            return
        }
        LxRouter.install.stalled = true

        // 2.把Vue构造函数记录到全局变量
        _Vue = Vue

        // 3.创建Vue实例时候传入的router对象注入到Vue实例上
        _Vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _Vue.prototype.$router = this.$options.router;
                    console.log(this.$options.router)
                    this.$options.router.init()
                }
            }
        })


    }

    /**
     * @description: 创建路由集合
     * @return {*}
     * @author: lx
     */
    createRouterMap() {
        this.options.routes.forEach(
            route => {
                this.routeMap[route.path] = route.component
            }
        )
        console.log(this.routeMap)
    }

    /**
     * @description: 初始化创建router-view,router-link组件
     * @return {*}
     * @author: lx
     */
    initComponents() {
        const self = this

        _Vue.component("router-link", {
            props: {
                to: String
            },
            // template: '<a :href="to"><slot></slot></a>',
            render(h) {
                return h("a", {
                    attrs: {
                        href: this.to,
                    },
                    on: {
                        click: this.clickHandler
                    },

                }, [this.$slots.default])
            },
            methods: {
                clickHandler(e) {
                    history.pushState({}, "", this.to)
                    this.$router.data.current = this.to
                    e.preventDefault();
                }
            }
        })

        _Vue.component("router-view", {
            render(h) {
                const component = self.routeMap[self.data.current]
                return h(component)
            }
        })
    }

    /**
     * @description: 对浏览器前进后退进行更新
     * @return {*}
     * @author: lx
     */
    initEvent() {
        window.addEventListener("popstate", () => {
            this.data.current = window.location.pathname
        })
    }
}
